#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    if (!QSslSocket::supportsSsl()) {
        qFatal("SSL support is not available.");
    }
    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &Widget::reply);

    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置HTTP头
    request.setUrl(QUrl("https://aip.baidubce.com/oauth/2.0/token"));

    QString data = "grant_type=client_credentials&client_id=YkTE3F24cpOJAEbejhJtFOCt&client_secret=neUiTu2HUH6lhhoZZF11GCYoip2CDEf6";
    manager->post(request, data.toLatin1()); // 请求token
}

Widget::~Widget()
{
    delete ui;
}

void Widget::reply(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll(); // 读取服务器返回的数据
        QJsonDocument doc = QJsonDocument::fromJson(data); // QByteArray -> QJsonDocument
        QJsonObject json = doc.object(); // QJsonDocument -> QJsonObject
        QString access_token = json.value("access_token").toString();
        qDebug() << "Token:" << access_token;
    } else {
        qDebug() << "Error:" << reply->errorString();
    }

    reply->deleteLater(); // 回收对象
}
